package study.alex.resumedb.gae.backend;

import com.google.appengine.api.ThreadManager;

import java.io.Serializable;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * Author: Alexey Kuznetsov
 * Date: 17.03.14
 * Time: 15:23
 * SVN $Id$
 */
public class Broadcaster implements Serializable {

    public interface BroadcastListener {
        void receiveBroadcast(String message);
    }

    private static LinkedList<BroadcastListener> listeners =
            new LinkedList<BroadcastListener>();

    public static synchronized void register(
            BroadcastListener listener) {
        listeners.add(listener);
    }

    public static synchronized void unregister(
            BroadcastListener listener) {
        listeners.remove(listener);
    }

    public static synchronized void broadcast(
            final String message) {
        for (final BroadcastListener listener: listeners)
            ThreadManager.createThreadForCurrentRequest(new Runnable() {
                @Override
                public void run() {
                    listener.receiveBroadcast(message);
                }
            }).start();
    }
}